import random
import d3dshot
import mss
import time
import requests
import base64
import io
import fitz
from PIL import Image
import os


def _d3dshot():

    # 创建d3dshot对象
    d = d3dshot.create()
    # 获取初始时间
    start_time = time.time()
    frame_count = 0
    # 设置一个时间窗口，比如1秒
    time_window = 1
    while time.time() - start_time < time_window:
        # 截取屏幕图片
        screenshot = d.screenshot()
        frame_count += 1
    # 计算帧率
    fps = frame_count / (time.time() - start_time)
    print(f"Estimated FPS: {fps:.2f}")

def _mss():


    # 初始化mss对象
    with mss.mss() as sct:
        # 获取初始时间
        start_time = time.time()
        frame_count = 0

        # 设置一个时间窗口，比如1秒
        time_window = 1

        while time.time() - start_time < time_window:
            # 截取屏幕图片
            sct_img = sct.grab(sct.monitors[0])
            frame_count += 1

        # 计算帧率
        fps = frame_count / (time.time() - start_time)
        print(f"Estimated FPS: {fps:.2f}")

def request_result(base64_img):
    try:
        headers = {
            "authority": "aidemo.youdao.com",
            "accept": "*/*",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
            "origin": "https://ai.youdao.com",
            "referer": "https://ai.youdao.com/",
            "sec-ch-ua": "\"Chromium\";v=\"122\", \"Not(A:Brand\";v=\"24\", \"Microsoft Edge\";v=\"122\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0"
        }
        url = "https://aidemo.youdao.com/ocrtransapi1"

        def generate_random_chinese_string():
            # 汉字的Unicode范围从\u4e00到\u9fff
            return ''.join(chr(random.randint(0x4e00, 0x9fff)) for _ in range(random.randint(1, 3)))
        data = {
            "imgBase":'data:image/png;base64,'+base64_img,
            "lang": "",
            "company": generate_random_chinese_string()
        }
        response = requests.post(url, headers=headers, data=data)
        result = response.json()
        # print(base64_img)
        # print(result)
        return result['renderImage']
    except Exception as e:
        print(f"request_result  Error: {e}")
        return None
def convert_pdf_to_images(pdf_path, output_folder):
    try:
        doc = fitz.open(pdf_path)
        total = doc.page_count
        for pg in range(total):
            page = doc[pg]
            pix = page.get_pixmap(dpi=300)
            if not os.path.exists(output_folder):
                os.mkdir(output_folder)
            save = os.path.join(output_folder, '%s.png' % (pg+1))
            pix.save(save)

            def image_to_base64(image_path):
                # 打开图片文件，并读取内容
                with open(image_path, "rb") as image_file:
                    # 对图片内容进行Base64编码
                    encoded_string = base64.b64encode(image_file.read())

                # 将bytes对象转换为字符串，并返回
                return encoded_string.decode('utf-8')

            # 使用示例
            base64_string = image_to_base64(save)
            strimg=request_result(base64_string)

            image_data = base64.b64decode(strimg)
            # 使用 io.BytesIO 将二进制数据转换为文件类对象
            image_file = io.BytesIO(image_data)
            # 使用 PIL 打开图片
            image = Image.open(image_file)
            # 保存图片到文件系统
            image.save(save)
    except Exception as e:
        print(f"convert_pdf_to_images Error: {e}")



def images_to_pdf(image_folder, output_pdf_path):
    try:
        print('image_folder',image_folder)
        print('output_pdf_path',output_pdf_path)
        # 获取文件夹中的所有图片文件
        images = [os.path.join(image_folder, file) for file in os.listdir(image_folder) if
                  file.endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]

        # 将图片文件按文件名排序，确保它们在PDF中的顺序
        images.sort()

        # 打开每张图片并添加到列表中
        img_list = []
        for img_path in images:
            img = Image.open(img_path)
            img_list.append(img)
        # 将图片列表保存为PDF
        img_list[0].save(output_pdf_path, save_all=True, append_images=img_list[1:])
        # 删除原始图片文件
        for img_path in images:
            os.remove(img_path)
    except Exception as e:
        print(f"images_to_pdf   Error: {e}")
if __name__ == '__main__':

    file='title.pdf'
    img_file='output_images'
    out_file=f'output_folder/{file}'
    convert_pdf_to_images(file,img_file)
    images_to_pdf(img_file,out_file)